
import requests
import json
import datetime

#应用消息，过于复杂，不适合页面扩展，暂时不使用
class SendMsg(object):
    def __init__(self):
        # self.corpid = myCof.get('wechat', 'corpid')
        # self.corpsecret = myCof.get('wechat', 'corpsecret')
        # self.agentid = myCof.get('wechat', 'agentid')
        pass


    def getToken(self):
        if self.corpid is None or self.corpsecret is None:
            return False, '企业微信相关信息未配置'
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + self.corpid + '&corpsecret=' + self.corpsecret
        response = requests.get(url)
        res = response.json()
        self.token = res['access_token']
        return True, '企业微信token获取成功'

    def sendMsg(self, msg):
        _isOK, result = self.getToken()
        if _isOK:
            url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.token
            jsonmsg = {
                   "touser" : "@all",
                   "msgtype" : "text",
                   "agentid" : self.agentid,
                   "text" : {
                       "content" : msg
                   },
                   "safe":0
                }
            data = (bytes(json.dumps(jsonmsg), 'utf-8'))
            requests.post(url, data, verify=False)
        else:
            print(result)



class Sendqyapi(object):
    def __init__(self):
        pass

    def sendqy_msg(self, **kwargs):
        """
        企业微信机器人消息

        """
        create_time = (kwargs['create_time'] + datetime.timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S')
        body = """计划名称：{} 
执行时间：{} 
总耗时长：{} ms 
用例总数：{} 条 
执行通过：{} 条 
执行失败：{} 条 
通 过 率：{} % 
报告链接：{} """.format(kwargs['planName'], create_time, kwargs['totalTime'],
                          kwargs['caseCount'], kwargs['passCount'], kwargs['failCount'],
                          str(kwargs['passRatio']), kwargs['reportUrl'])    #.encode("utf-8").decode("latin1"),之前用的参数，后面企业微信把入参格式改了，先不管了

        data ={"msgtype": "text", "text": {"content":  str(body)}}
        headers = {}
        headers['Content-Type'] = 'application/json'
        res = requests.post(url=kwargs['webhook'], headers=headers, json=data)
        # print(res.content)


# body = """       xxxx测试计划
# 执行时间：yyyy-MM-dd tt:mm:ss
# 总耗时长：100000ms
# 用例总数：100 条
# 执行通过：99 条
# 执行失败：1 条
# 通过比率：99%
# 报告链接：http://xxxx.xxx/xxx/xxx/sdfsfsdf.html""".encode("utf-8").decode("latin1")
#
# data = """
#     {
#         "msgtype": "text",
#         "text": {
#             "content": " """ + str(body) + """"
#         }
#    }
# """
# url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=0a31a330-9332-4e19-a84e-dd1bd12b98e3'
# headers={}
# headers['Content-Type'] = 'application/json'
#
#
# res = requests.post(url=url, headers=headers, data=data)
# print(res.content)



# wechatMsg = SendMsg()
# wechatMsg.sendMsg('API接口从无到有')


#aa = '2021-07-30 02:29:01.309364'

# import datetime
# s = '2021-01-18T11:18:10.833876+00:00'
# dt = datetime.datetime.fromisoformat(aa)   #将字符串变成时间
#
# print(aa)
# # 2021-01-18 11:18:10.833876+00:00
# print(dt + datetime.timedelta(hours=8))
# datetime.datetime(2021, 1, 18, 11, 18, 10, 833876, tzinfo=datetime.timezone.utc)

# aaa = 'Hi，我是机器人接口测试机器人\n由谭志良于07月28日添加到群'
# name = "计划名称：示例计划".encode('utf-8').decode('latin1')
# time = "执行时间：2021-08-17 17:58:40".encode('utf-8').decode('latin1')
# hao = '总耗时长：15.37 ms'.encode('utf-8').decode('latin1')
# count = '用例总数：2 条'.encode('utf-8').decode('latin1')
# passcount = '执行通过：2 条'.encode('utf-8').decode('latin1')
# faildcount = '执行失败：0 条'.encode('utf-8').decode('latin1')
# passRatio = '通 过 率：100.0 %'.encode('utf-8').decode('latin1')
# reportUrl = '报告链接：http://172.56.140.2:5001/planexerep?excutnum=2021081717583972'.encode('utf-8').decode('latin1')
#
# bbb = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n".format(name,time,hao,count,passcount,faildcount,passRatio,reportUrl)
# data = {"msgtype": "text", "text": {"content": bbb }}
# url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=0a31a330-9332-4e19-a84e-dd1bd12b98e3'
# headers={}
# headers['Content-Type'] = 'application/json'
# res = requests.post(url=url, headers=headers, json=data, verify=False)
# print(res.content)
# print(bbb)